#!/bin/sh
# PCP QA Test No. 1701
# Exercise the bpftrace PMDA - histograms
#

seq=`basename $0`
echo "QA output created by $seq"

. ./common.bpftrace

_pmdabpftrace_check

status=1       # failure is the default!

_prepare_pmda bpftrace
trap "_pmdabpftrace_cleanup; exit \$status" 0 1 2 3 15
_stop_auto_restart pmcd


_script_id_filter()
{
    sed -E -e 's/bpftrace.scripts.([a-z0-9]+).([a-z]+)/bpftrace.scripts.UUID.\2/g'
}

# probe to see if bpftrace works at all
#
if which bpftrace >/dev/null
then
    if $sudo bpftrace -e 'BEGIN { printf("foo\n"); exit() }' >$tmp.tmp
    then
	if grep '^foo$' $tmp.tmp >/dev/null
	then
	    echo "bpftrace: OK" >>$seq_full
	else
	    cat $tmp.tmp >>$seq_full
	    echo "bpftrace: ran OK but no the expected output" >>$seq_full
	fi
    else
	cat $tmp.tmp >>$seq_full
	echo "bpftrace: failed" >>$seq_full
    fi
else
    echo "bpftrace: not installed" >>$seq_full
fi

# real QA test starts here
cat <<EOF | _pmdabpftrace_install
# Installed by PCP QA test $seq on `date`
[dynamic_scripts]
enabled = true
auth_enabled = false
EOF

echo "=== start bpftrace script ==="
script_id=`./src/store_and_fetch bpftrace.control.register "BEGIN { @h = hist(-2); @h = hist(1); @h = hist(100); @h = hist(1000); exit(); }" | \
  python3 -c 'import sys,json; print(json.loads(sys.stdin.read())["script_id"])'`
_pmdabpftrace_wait_for_value bpftrace.scripts.${script_id}.data.h | _script_id_filter

echo "=== check metrics ==="
pminfo -dfmtT bpftrace.scripts.${script_id}.data.h | _script_id_filter


_pmdabpftrace_remove
status=0
exit
